import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap, finalize } from "rxjs/operators"
import { Router } from "@angular/router"

import { MessageService } from "../h-services/message.service"

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

  constructor(
    private router: Router,
    private message: MessageService
  ) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      tap(success => {
        if (success instanceof HttpResponse) {
        }
      }, error => {
        /* 
          401 token 失效
          403 权限不足
        */
        if (error instanceof HttpErrorResponse) {
          if (error.status != 200 && error.status != 401) {
            console.log(error);
            this.message.addErrorMessage({
              type: 1,
              message: error.error.message || "系统错误"
            })
          }
          if (error.status == 401) {
            this.router.navigate(["login"])
          }
        }
      }),
      finalize(() => {
      })
    );
  }
}
